﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using SQLite.NET;
using System.Text.RegularExpressions;
using System.Diagnostics;




namespace BierdopjeTV.Import
{
    class EpisodeParser
    {
         #region Fields

        //Lookup
        private int m_ShowID;
        //parse
        private string m_ShowName;
        private int m_Season; 
        private int m_Episode;        
        private string m_Codec;
        private string m_Source;
        private string m_Group;
        private string m_Path;
        private int m_SubNLDownloaded;
        private int m_SubENDownloaded; 
        
        public bool isParsed = false;

        #endregion


        #region Properties
        
        public int ShowID
        {
            get { return m_ShowID; }
            set { m_ShowID = value; }
        }

        public string ShowName
        {
            get { return m_ShowName; }
            set { m_ShowName = value; }
        }

        public int Season
        {
            get { return m_Season; }
            set { m_Season = value; }
        }

        public int Episode
        {
            get { return m_Episode; }
            set { m_Episode = value; }
        }
 
        public string Codec
        {
            get { return m_Codec; }
            set { m_Codec = value; }
        }
        public string Source
        {
            get { return m_Source; }
            set { m_Source = value; }
        }
        public string Group
        {
            get { return m_Group; }
            set { m_Group = value; }
        }

        public string Path
        {
            get { return m_Path; }
            set { m_Path = value; }
        }

        public int SubNLDownloaded
        {
            get { return m_SubNLDownloaded; }
            set { m_SubNLDownloaded = value; }
        }

        public int SubENDownloaded
        {
            get { return m_SubENDownloaded; }
            set { m_SubENDownloaded = value; }
        }

        #endregion

        public EpisodeParser ParseEpisode(string Path)
        //public void ParseEpisode(string Path)
        {

            this.Path = Path;
            string ParsePath = Path;
            ParsePath = ParsePath.Replace(" ", ".");
            ParsePath = ParsePath.Replace("_", ".");
   
            
            
            List<string> Patterns = new List<string>();

            //SeriesName.S01E01.HDTV.720p-GROUPNAME
            Patterns.Add(@"\\(?<SeriesName>\w.+)(S)(?<Season>\d{2})(E)(?<Episode>\d{2}).+(?<Source>HDTV|PDTV|DVDRIP|DSR|SDTV).(?<Codec>x264|XviD|DivX)?-?(?<Group>\w+)");
            //SeriesName.1x01.HDTV.XviD-GROUPNAME
            Patterns.Add(@"\\(?<SeriesName>\w.+)(?<Season>\d{1,2})x(?<Episode>\d{1,2}).+(?<Source>HDTV|PDTV|DVDRIP|DSR|SDTV).(?<Codec>x264|XviD|DivX)?-?(?<Group>\w+)");
            //SeriesName.S01E01.720p.iTunes.x264-GROUP
            Patterns.Add(@"\\(?<SeriesName>\w.+)(S)(?<Season>\d{2})(E)(?<Episode>\d{2}).+(?<Source>WEB-DL|iTunes).+(?<Codec>AVC|H264|h.264|x264)(-|.|\s)(?<Group>.+)");

            
            
            foreach (string pattern in Patterns)
            {
                if (IsParseAble(ParsePath, pattern))
                {
                    ExecuteParse(ParsePath, pattern);
                    isParsed = true;
                    addEpisode(this); //add item to database
                    break;
                }
                

            }
         
            return this;
        }

        private bool IsParseAble(string pathParse, string pattern)
        {
            Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
            return r.Match(pathParse).Success;
        }

        private static string getRealShowName(string source)
        {
            int lastBackSlash = source.LastIndexOf(@"\") + 1;
            int length = source.Length - lastBackSlash;

            return source.Substring(lastBackSlash, length).Replace(".", " ").Trim();
        } 


        private void ExecuteParse(string pathParse, string pattern)
        {           
            Debug.Print("pathParse: " + pathParse);
            Debug.Print("Path: " + Path);
            Regex r = new Regex(pattern, RegexOptions.IgnoreCase);

            this.ShowName = getRealShowName(r.Match(pathParse).Result("${SeriesName}"));
            //If showname is filled
            if (this.ShowName.Length > 0)
            {
                this.ShowID = API.BierdopjeShows.getShowID(this.ShowName);
            }
            this.Season = Convert.ToByte(r.Match(pathParse).Result("${Season}"));
            this.Episode = Convert.ToByte(r.Match(pathParse).Result("${Episode}"));
            this.Codec = r.Match(pathParse).Result("${Codec}");
            this.Source = r.Match(pathParse).Result("${Source}");
            this.Group = r.Match(pathParse).Result("${Group}");
            if (subTitleExists(Path, "nl"))
            {
                this.SubNLDownloaded = 1;                
            }

            if (subTitleExists(Path, "en"))
            {
                this.SubENDownloaded = 1;             
            }
        }

        private bool subTitleExists(string filepath, string language)
        {
            string SubtitleName;

            FileInfo file = new FileInfo(filepath);
            SubtitleName = filepath.Replace(file.Extension, "." + language + ".srt");

            if (File.Exists(SubtitleName))
            {
                return true;
            }
            else
            {
                return false;
            }                    
        }


        public static void addEpisode(EpisodeParser Episode)
        {
            string _Query;

            SQLiteResultSet _Results;
            _Query = "";
            _Query += "SELECT" + Environment.NewLine;
            _Query += "	Path," + Environment.NewLine;
            _Query += "	SubNL," + Environment.NewLine;
            _Query += "	SubEN" + Environment.NewLine;
            _Query += "FROM" + Environment.NewLine;
            _Query += "	Episodes" + Environment.NewLine;
            _Query += "WHERE  " + Environment.NewLine;
            _Query += "	ShowID = " + Episode.ShowID + Environment.NewLine;
            _Query += "	AND " + Environment.NewLine;
            _Query += "	Season = " + Episode.Season + Environment.NewLine;
            _Query += "	AND " + Environment.NewLine;
            _Query += "	Episode = " + Episode.Episode + Environment.NewLine;
            _Query += "	AND " + Environment.NewLine;
            _Query += "	Codec = '" + Episode.Codec + "'" + Environment.NewLine;
            _Query += "	AND " + Environment.NewLine;
            _Query += "	Source = '" + Episode.Source + "'" + Environment.NewLine;


            //Check if current episode is already in the database!
            _Results = Helpers.SqliteHelper.ExecuteQuery(_Query);

            int rijen = _Results.Rows.Count;

            //If the current episode already exists
            if (rijen > 0)
            {
                //If the filepath is not the same as dataase
                if (
                    _Results.Rows[0].fields[0] != Episode.Path || 
                    _Results.Rows[0].fields[1] != Episode.SubNLDownloaded.ToString() ||
                    _Results.Rows[0].fields[2] != Episode.SubENDownloaded.ToString()
                   )
                {
                    //path, subnl or suben is wrong, update!
                    Helpers.SqliteHelper.ExecuteQuery(@"UPDATE Episodes" +
                                " SET " +
                                " Path = \'" + Episode.Path + "\'" +
                                " AND" +
                                " SubNL = " + Episode.SubNLDownloaded +
                                " AND" +
                                " Episode = " + Episode.SubENDownloaded +                                
                                " WHERE " +
                                " ShowID = " + Episode.ShowID +
                                " AND" +
                                " Season = " + Episode.Season +
                                " AND" +
                                " Episode = " + Episode.Episode +
                                " AND" +
                                " Codec = '" + Episode.Codec + "'" +
                                " AND" +
                                " Source = '" + Episode.Codec + "'"
                               );

                    
                }
            }
            else //the episode was not yet in the database.
            {
                Helpers.SqliteHelper.ExecuteQuery(@"INSERT INTO Episodes" +
                            "(" +
                            "    Path, ShowId, Season, Episode, SubNL, SubEN, Codec, Source" +
                            ")" +
                            "VALUES" +
                            "(" +
                            "    \'" + Episode.Path + "\'," +
                            "    " + Episode.ShowID + "," +
                            "    " + Episode.Season + "," +
                            "    " + Episode.Episode + "," +
                            "    " + Episode.SubNLDownloaded + "," +
                            "    " + Episode.SubENDownloaded + "," +
                            "    \'" + Episode.Codec + "\'," +
                            "    \'" + Episode.Source + "\'" +
                            ")"
                           );

                Helpers.Logger.WriteSimpel("Episde added!!! (" + Episode.Path + ")");

            }


        }


        private static string dbSave(string source)
        {
            return source.Replace("'", "''");
        }
        
    }
}
